package org.example.mywebsite.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.mywebsite.entity.Music;
import org.example.mywebsite.mapper.MusicMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/music")
@Tag(name = "音乐接口")
@Slf4j
public class MusicController {

    private final MusicMapper musicMapper;

    @PostMapping("/upload")
    @Transactional
    @Operation(summary = "上传音乐")
    public String upload(MultipartFile music) throws  Exception {
        log.info("上传音乐:{}", music);
        try{
            String basePath = "C:/Users/Administrator/Desktop/vscode/Vue/vue-project/public/Music/";
            String filename = music.getOriginalFilename();

            Music newMusic = new Music();
            int id = musicMapper.selectList(null).size();
            String musicName = filename.substring(0, filename.lastIndexOf("."));
            String url="/Music/"+filename;
            newMusic.setId(id);
            newMusic.setName(musicName);
            newMusic.setUrl(url);
            musicMapper.insert(newMusic);

            music.transferTo(new File(basePath + filename));
        } catch (Exception e) {
            log.error("上传失败:{}", e);
            throw new RuntimeException(e);
        }
        return "上传成功";
    }

    @GetMapping("/list")
    @Operation(summary = "获取音乐列表")
    public List<Music> list() {
        log.info("获取音乐列表:{}");
        return musicMapper.selectList(null);
    }
}
